package kz.pompei.ifacer.visio.def.paint.grid;

import java.util.ArrayList;
import java.util.List;

import kz.pompei.ifacer.model.widgets.WidgetGrid;
import kz.pompei.ifacer.util.RichText;
import kz.pompei.ifacer.util.Util;

public class Grid {
  
  public enum RowType {
    NORMAL, HEAD, SEL;
    
    static RowType parse(char c) {
      if (c == ' ') return NORMAL;
      if (c == 'S') return SEL;
      if (c == 's') return SEL;
      if (c == 'H') return HEAD;
      if (c == 'h') return HEAD;
      return NORMAL;
    }
  }
  
  private static final RichText EMPTY = RichText.parse("");
  
  public class Row {
    RowType type = RowType.NORMAL;
    final List<RichText> cells = new ArrayList<>();
    
    RichText get(int col) {
      if (col < cells.size()) {
        RichText ret = cells.get(col);
        if (ret == null) return EMPTY;
        return ret;
      }
      return EMPTY;
    }
  }
  
  private final List<Integer> widths = new ArrayList<>();
  public final List<Row> rows = new ArrayList<>();
  private int colCount = 0;
  
  public void setContents(String contents) {
    rows.clear();
    colCount = 0;
    for (String line : contents.split("\\n")) {
      if (line.length() == 0) continue;
      Row row = new Row();
      rows.add(row);
      row.type = RowType.parse(line.charAt(0));
      for (String cell : line.substring(1).split("\\|")) {
        row.cells.add(RichText.parse(cell.trim()));
      }
      if (colCount < row.cells.size()) colCount = row.cells.size();
    }
  }
  
  public void setWidths(String s) {
    widths.clear();
    if (s == null) return;
    for (String sw : s.split(",")) {
      widths.add(Integer.valueOf(sw));
    }
  }
  
  public String getWidths() {
    return Util.join(",", widths);
  }
  
  public void clean() {
    widths.clear();
    rows.clear();
  }
  
  public int colCount() {
    return colCount;
  }
  
  public int rowCount() {
    return rows.size();
  }
  
  public int getColWidth(int col) {
    int ret = getCollWidthInner(col);
    if (ret < 10) ret = 10;
    return ret;
  }
  
  private int getCollWidthInner(int col) {
    if (col < widths.size()) return widths.get(col);
    return 0;
  }
  
  public void setColWidth(int col, int width) {
    while (col >= widths.size()) {
      widths.add(0);
    }
    widths.set(col, width);
  }
  
  public void assign(WidgetGrid w) {
    setContents(w.contents);
    setWidths(w.widths);
  }
}
